<template>
  <div class="app-container">
    <div class="content">
      <!-- 左侧垂直按钮区域 -->
      <div class="button-panel">
        <div class="action-group">
          <el-button
            type="primary"
            plain
            size="small"
            @click="handleAddEnvSpectrum"
          >
            环境光谱
          </el-button>
          <div v-if="envSpectrumNo" class="id-text">
            编号：{{ envSpectrumNo }}
          </div>
        </div>

        <div class="action-group">
          <el-button
            type="primary"
            plain
            size="small"
            @click="handleImportModel"
          >
            导入模型
          </el-button>
          <div v-if="modelNo" class="id-text">编号：{{ modelNo }}</div>
        </div>

        <div class="action-group">
          <el-button
            type="primary"
            plain
            size="small"
            @click="handleImportSampleSpectrum"
          >
            导入样品光谱
          </el-button>
          <div v-if="sampleSpectrumNo" class="id-text">
            编号：{{ sampleSpectrumNo }}
          </div>
        </div>

        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportExcelSpectrum"
        >
          导入excel光谱
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleStartAnalysis"
        >
          开始分析
        </el-button>
      </div>

      <!-- 图表区域 -->
      <div class="left-chart">
        <div class="chart-title">样品吸光度曲线</div>
        <div ref="chartRef" class="chart-area" />
      </div>
    </div>

    <div class="table">
      <el-table
        v-loading="loading"
        :data="dfbList"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column
          label="分析结果编号"
          align="center"
          prop="onlineResultNo"
        />
        <el-table-column
          label="成分名称"
          align="center"
          prop="constituentName"
        />
        <el-table-column label="预测值" align="center" prop="predicted" />
        <el-table-column label="模型编号" align="center" prop="modelNo" />
        <el-table-column
          label="部门名称"
          align="center"
          prop="departmentName"
        />
        <el-table-column label="仪器编号" align="center" prop="instrumentNo" />
        <el-table-column
          label="仪器名称"
          align="center"
          prop="instrumentName"
        />
        <el-table-column
          label="采样时间"
          align="center"
          prop="samplingTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.samplingTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['analysis:dfb:edit']"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              v-hasPermi="['analysis:dfb:remove']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 导入模型 -->
    <el-dialog
      title="模型"
      :visible.sync="modelDataDialogVisible"
      width="80vw"
      append-to-body
    >
      <model-data
        ref="modelData"
        :is-row-visible="false"
        @selection-change="handleModelRowSelection"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitModelDataForm">确 定</el-button>
        <el-button @click="modelDataDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入环境光谱 -->
    <el-dialog
      title="环境光谱"
      :visible.sync="envSpectrumDialogVisible"
      width="80vw"
      append-to-body
    >
      <env-spectrum-detail
        ref="envData"
        :is-row-visible="false"
        @selection-change="handleSelectionChangeEnvSpectrum"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEnvForm">确 定</el-button>
        <el-button @click="envSpectrumDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入样品光谱 -->
    <el-dialog
      title="样品光谱"
      :visible.sync="sampleSpectrumDialogVisible"
      width="30vw"
      append-to-body
    >
      <div
        style="
          display: flex;
          justify-content: center;
          gap: 16px;
          margin-top: 20px;
        "
      >
        <el-button
          type="primary"
          @click="handleAddZlaSpectrum"
        >制粒一样品光谱</el-button>
        <el-button @click="handleAddZlbSpectrum">制粒二样品光谱</el-button>
      </div>
    </el-dialog>

    <!-- 制粒一样品光谱 -->
    <el-dialog
      title="制粒一样品光谱"
      :visible.sync="zlaSpectrumDialogVisible"
      width="80vw"
      append-to-body
    >
      <zla-spectrum-detail
        ref="zlaData"
        :is-row-visible="false"
        @selection-change="handleSelectionZlaSpectrum"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSampleForm">确 定</el-button>
        <el-button @click="zlaSpectrumDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 制粒二样品光谱 -->
    <el-dialog
      title="制粒二样品光谱"
      :visible.sync="zlbSpectrumDialogVisible"
      width="80vw"
      append-to-body
    >
      <zlb-spectrum-detail
        ref="zlbData"
        :is-row-visible="false"
        @selection-change="handleSelectionZlbSpectrum"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSampleForm">确 定</el-button>
        <el-button @click="zlbSpectrumDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOffline,
  getAnalyzePayload
} from '@/api/analysis/offline'
import EnvSpectrumDetail from '@/views/spectrum/env_spectrum/index.vue'
import ZlaSpectrumDetail from '@/views/spectrum/zla_spectrum/index.vue'
import ZlbSpectrumDetail from '@/views/spectrum/zlb_spectrum/index.vue'
import ModelData from '@/views/model/data/index.vue'

export default {
  name: 'Dfb',
  components: {
    EnvSpectrumDetail,
    ModelData,
    ZlaSpectrumDetail,
    ZlbSpectrumDetail
  },
  data() {
    return {
      modelNo: '', // 模型编号
      sampleSpectrumNo: '', // 样品光谱编号
      envSpectrumNo: '', // 环境光谱编号

      selectedEnvSpectrum: null, // 选中的环境光谱数据
      selectedModelData: null, // 选中的模型数据
      selectedSampleSpectrum: null, // 选中的样品光谱数据

      envSpectrumDialogVisible: false,
      modelDataDialogVisible: false,
      sampleSpectrumDialogVisible: false,
      zlaSpectrumDialogVisible: false,
      zlbSpectrumDialogVisible: false,
      // 遮罩层
      loading: true,
      // 干燥流化床车间在线分析历史表格数据
      dfbList: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        onlineResultNo: null,
        constituentId: null,
        constituentName: null,
        predicted: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        modelId: null,
        modelNo: null,
        samplingTime: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        modifierId: null,
        modifier: null,
        modifyTime: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    submitSampleForm() {
      if (this.zlaSpectrumDialogVisible) {
        this.sampleSpectrumNo = this.selectedSampleSpectrum.sampleSpectrumPelNo
        this.zlaSpectrumDialogVisible = false
      } else if (this.zlbSpectrumDialogVisible) {
        this.sampleSpectrumNo = this.selectedSampleSpectrum.sampleSpectrumDfbNo
        this.zlbSpectrumDialogVisible = false
      }
      this.sampleSpectrumDialogVisible = false
      console.log('提交选中的样品光谱', this.selectedSampleSpectrum)
    },
    handleAddZlaSpectrum() {
      this.zlaSpectrumDialogVisible = true
    },
    handleAddZlbSpectrum() {
      this.zlbSpectrumDialogVisible = true
    },
    handleStartAnalysis() {
      // 检查是否选择了必要的数据
      console.log(
        '开始分析',
        this.selectedEnvSpectrum,
        this.selectedModelData,
        this.selectedSampleSpectrum
      )
      if (
        !this.selectedEnvSpectrum.envSpectrumNo ||
        !this.selectedModelData.modelId ||
        !this.selectedSampleSpectrum.sampleSpectrumPelNo
      ) {
        this.$message.warning('请先选择环境光谱、模型和样品光谱数据！')
        return
      }

      // 构造请求参数
      const payload = {
        envSpectrumNo: this.selectedEnvSpectrum.envSpectrumNo,
        modelId: this.selectedModelData.modelId,
        sampleSpectrumNo:
          this.selectedSampleSpectrum.sampleSpectrumPelNo ||
          this.selectedSampleSpectrum.sampleSpectrumDfbNo
      }

      getAnalyzePayload(payload)
        .then((response) => {
          if (response.code === 200) {
            this.$message.success('分析完成')
            console.log('返回结果', response)
            // 刷新列表
            this.getList()
          } else {
            this.$message.error(response.msg || '分析失败')
          }
        })
        .catch((error) => {
          this.$message.error('分析请求失败')
          console.error('分析请求失败:', error)
        })
    },
    handleImportExcelSpectrum() {
      this.$message.info('功能正在开发中，敬请期待！...')
    },
    handleImportSampleSpectrum() {
      this.sampleSpectrumDialogVisible = true
    },
    submitModelDataForm() {
      this.modelDataDialogVisible = false
      if (this.selectedModelData) {
        // 处理选中的模型数据
        this.modelNo = this.selectedModelData.modelNo // 假设模型数据有 modelNo 字段
        // 调用函数获取模型数据，存储起来
        // model_details表里面获取coef 数组，获取intercept，获取
        // 干脆写一个接口，后台直接根据模型编号和样品光谱编号获得json
        console.log('提交选中的模型数据', this.selectedModelData)
      } else {
        this.$message.warning('请先选择一个模型数据')
      }
    },
    handleImportModel() {
      this.modelDataDialogVisible = true
    },
    submitEnvForm() {
      this.envSpectrumNo = this.selectedEnvSpectrum.envSpectrumNo
      this.envSpectrumDialogVisible = false
    },
    handleSelectionZlaSpectrum(selection) {
      const tableRef = this.$refs.zlaData.$refs.zlaSpectrumTable
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1]
        this.$nextTick(() => {
          tableRef.clearSelection() // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true) // 仅保留当前选中
        })
        this.selectedSampleSpectrum = lastSelected
      } else {
        this.selectedSampleSpectrum = selection[0] || null
      }
      console.log('查看选中的制粒一样品光谱', this.selectedSampleSpectrum)
    },
    handleSelectionZlbSpectrum(selection) {
      const tableRef = this.$refs.zlbData.$refs.zlbSpectrumTable
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1]
        this.$nextTick(() => {
          tableRef.clearSelection() // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true) // 仅保留当前选中
        })
        this.selectedSampleSpectrum = lastSelected
      } else {
        this.selectedSampleSpectrum = selection[0] || null
      }
      console.log('查看选中的制粒二样品光谱', this.selectedSampleSpectrum)
    },
    handleModelRowSelection(selection) {
      const tableRef = this.$refs.modelData.$refs.modelTable
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1]
        this.$nextTick(() => {
          tableRef.clearSelection() // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true) // 仅保留当前选中
        })
        this.selectedModelData = lastSelected
      } else {
        this.selectedModelData = selection[0] || null
      }
      console.log('查看选中的模型数据', this.selectedModelData)
    },
    handleSelectionChangeEnvSpectrum(selection) {
      const tableRefEnv = this.$refs.envData.$refs.envTable
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1]
        this.$nextTick(() => {
          tableRefEnv.clearSelection() // 清除所有选中
          tableRefEnv.toggleRowSelection(lastSelected, true) // 仅保留当前选中
        })
        this.selectedEnvSpectrum = lastSelected
      } else {
        this.selectedEnvSpectrum = selection[0] || null
      }
      console.log('查看选中的环境光谱', this.selectedEnvSpectrum)
    },

    handleAddEnvSpectrum() {
      this.envSpectrumDialogVisible = true
    },
    handleViewHistory() {
      this.$router.push('/dfb_history')
    },
    /** 查询干燥流化床车间在线分析历史列表 */
    getList() {
      this.loading = true
      listOffline(this.queryParams).then((response) => {
        this.dfbList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.onlineResultId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>
<style scoped>
.action-group {
  display: flex;
  flex-direction: column;
}

.id-text {
  font-size: 12px;
  color: #409eff;
  margin-top: 4px;
}

.header {
  display: flex;
  justify-content: space-around;
}

.content {
  display: flex;
  justify-content: space-between;
  height: 60%; /* 减去头部和底部的高度 */
  margin: 5px 0;
}

.right-chart {
  width: 49.5%;
  border: 1px solid #ddd;
}

.chart-title {
  font-size: 1.2em;
  margin-bottom: 10px;
  text-align: center;
}

.chart-area {
  height: 35vh; /* 根据实际需要调整高度 */
  background-color: #f9f9f9;
}

.content {
  display: flex;
  height: 100%;
}

.button-panel {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 保证所有按钮左对齐 */
  justify-content: space-between; /* 自动拉开间距 */
  margin-right: 20px;
  padding: 0;
}

.button-panel .el-button {
  margin: 0; /* 清除可能的默认 margin */
}

.left-chart {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-title {
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
